#!/usr/bin/env python
"""
eBay用户令牌获取脚本

运行此脚本来获取eBay用户令牌（如果您还没有的话）
"""

import requests
import base64
import webbrowser
from urllib.parse import urlencode, parse_qs, urlparse

class EbayTokenHelper:
    def __init__(self, app_id, cert_id, redirect_uri='urn:ietf:wg:oauth:2.0:oob'):
        self.app_id = app_id
        self.cert_id = cert_id
        self.redirect_uri = redirect_uri
        self.sandbox = True  # 设置为False使用生产环境
        
        if self.sandbox:
            self.auth_base_url = 'https://auth.sandbox.ebay.com/oauth2/authorize'
            self.token_url = 'https://api.sandbox.ebay.com/identity/v1/oauth2/token'
        else:
            self.auth_base_url = 'https://auth.ebay.com/oauth2/authorize'
            self.token_url = 'https://api.ebay.com/identity/v1/oauth2/token'
    
    def get_authorization_url(self, scopes=None):
        """生成授权URL"""
        if scopes is None:
            scopes = [
                'https://api.ebay.com/oauth/api_scope',
                'https://api.ebay.com/oauth/api_scope/sell.marketing.readonly',
                'https://api.ebay.com/oauth/api_scope/sell.marketing',
                'https://api.ebay.com/oauth/api_scope/sell.inventory.readonly',
                'https://api.ebay.com/oauth/api_scope/sell.inventory',
            ]
        
        params = {
            'client_id': self.app_id,
            'redirect_uri': self.redirect_uri,
            'response_type': 'code',
            'scope': ' '.join(scopes),
            'state': 'state123'  # 用于安全验证
        }
        
        auth_url = f"{self.auth_base_url}?{urlencode(params)}"
        return auth_url
    
    def exchange_code_for_token(self, authorization_code):
        """用授权码换取访问令牌"""
        # 创建Basic Auth头
        credentials = f"{self.app_id}:{self.cert_id}"
        encoded_credentials = base64.b64encode(credentials.encode()).decode()
        
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': f'Basic {encoded_credentials}'
        }
        
        data = {
            'grant_type': 'authorization_code',
            'code': authorization_code,
            'redirect_uri': self.redirect_uri
        }
        
        response = requests.post(self.token_url, headers=headers, data=data)
        
        if response.status_code == 200:
            return response.json()
        else:
            raise Exception(f"Token exchange failed: {response.status_code} - {response.text}")

def main():
    print("eBay用户令牌获取助手")
    print("=" * 40)
    
    # 获取用户输入
    print("请输入您的eBay API凭证:")
    app_id = input("App ID (客户端ID): ").strip()
    cert_id = input("Cert ID (客户端密钥): ").strip()
    
    if not app_id or not cert_id:
        print("错误：App ID和Cert ID不能为空！")
        return
    
    # 创建token助手
    helper = EbayTokenHelper(app_id, cert_id)
    
    # 生成授权URL
    auth_url = helper.get_authorization_url()
    
    print(f"\n步骤1：请访问以下URL进行授权:")
    print(f"{auth_url}")
    print(f"\n正在自动打开浏览器...")
    
    try:
        webbrowser.open(auth_url)
    except:
        print("无法自动打开浏览器，请手动复制上面的URL到浏览器中打开")
    
    print(f"\n步骤2：完成授权后，您会被重定向到一个页面")
    print(f"步骤3：从重定向URL中复制'code'参数的值")
    
    authorization_code = input("\n请输入授权码(code): ").strip()
    
    if not authorization_code:
        print("错误：授权码不能为空！")
        return
    
    try:
        # 交换令牌
        print("\n正在获取访问令牌...")
        token_data = helper.exchange_code_for_token(authorization_code)
        
        print("\n✓ 成功获取令牌！")
        print("=" * 40)
        print(f"访问令牌: {token_data.get('access_token')}")
        print(f"令牌类型: {token_data.get('token_type')}")
        print(f"过期时间: {token_data.get('expires_in')} 秒")
        
        if 'refresh_token' in token_data:
            print(f"刷新令牌: {token_data.get('refresh_token')}")
        
        print("\n请将访问令牌配置到settings.py中:")
        print(f"EBAY_AUTH_TOKEN = '{token_data.get('access_token')}'")
        
    except Exception as e:
        print(f"\n错误：{e}")

if __name__ == "__main__":
    main() 